/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAL;

import java.sql.*;

/**
 *
 * @author Vien-IT
 */
public class ConnectData {
    
    private Connection connect = null;
    private Statement statement = null;
    private ResultSet result = null;

    public ConnectData() {
    }
    
    public Connection getConnect () throws Exception
    {
        try {
             if(this.connect == null || this.connect.isClosed())
         {
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                connect = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=bkq_shop", "sa", "123456");
         }
        } catch (Exception e) {
            throw  new Exception("khong the tao ket noi den csdl");
        }
          return this.connect;
    }
    
    public Statement getStatement() throws Exception
    {
      
       try {
            this.statement = this.getConnect().createStatement();
        } catch (Exception e) {
            throw  new Exception("khong the tao Statement cho ket noi");
       
       }
        
        return this.statement;
    }
    
    public ResultSet executeQuery(String query) throws Exception
    {
        try {
            this.result = this.getStatement().executeQuery(query); 
        } catch (Exception e) {
            throw new Exception("khong the truy van cau lenh "+ query);
        }
        
        return this.result;
    }
    
    
    public int executeUpdate(String sql) throws SQLException 
    {
        int rs = -1;
        try {
            rs = this.getStatement().executeUpdate(sql);
             System.out.println(rs);
            
        } catch (Exception e) {
           System.out.println("Khong the thuc thi cau lenh "+ sql);
        }
        this.close();
        return rs;
    }
    
    public void close() 
    {
        try {
             if(this.result != null )
        {
            this.result.close();
        }
        
        if(this.statement != null )
        {
            this.statement.close();
        }
        
        if(this.connect != null )
        {
            this.connect.close();
        }
        } catch (Exception e) {
            System.out.println("ham close day ma " + e);
        }
    }
    
    
    
}
